<?php

/* 连接 MySQL */
function connect_mysql() {
    $servername = "localhost";
    $username   = "eshopManager";
    $password   = "123456";
    $database   = "eshop";

    // 创建连接
    $conn = new mysqli($servername, $username, $password, $database);
    
    // 检测连接
    if ($conn->connect_error) {
        die("连接失败: " . $conn->connect_error);
    }

    $conn->select_db("eshop");

    return $conn;
}

function check_keys(array $array, ...$keys): bool {
    foreach ($keys as $key) {
        if (!array_key_exists($key, $array)) {
            return false;
        }
    }
    return true;
}

function getJsonDataFromRawInput() {
    $json_raw = file_get_contents("php://input");

    $json = json_decode($json_raw, true);
    
    return $json;
}

function getUserIdBySessionId(mysqli $conn): ?string {
    $user_id = null;

    if (!check_keys($_COOKIE, "sessionID")) {
        return null;
    }

    $session_id = $_COOKIE["sessionID"];

    $query_str = "SELECT userID FROM Session WHERE ID = '$session_id';";
    $query = $conn->query($query_str);

    if ($user_id_data = $query->fetch_row()) {
        $user_id = $user_id_data[0];
    } else {
        $user_id = null;
    }

    $query->close();

    return $user_id;
}

function getUserPermissionByUserId(mysqli $conn, string $user_id): int {
    $query_str = "SELECT permission FROM User WHERE ID = $user_id;";

    $query = $conn->query($query_str);
    $permission = $query->fetch_row();

    $query->close();

    return (int)$permission[0];
}

?>